package com.fcat.springboot.core.service.impl;

import com.fcat.base.common.util.DateUtil;
import com.fcat.springboot.core.service.LogService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;

@Service
public class LogServiceImpl implements LogService {
    @Value("${logging.file.path}")
    private String myLogPath;



    @Override
    @Async("taskExecutor")
    public void info(String deviceId, String content) {
        recordLog(deviceId,content);
    }

    private void recordLog(String deviceId, String content) {
        String fileName = DateUtil.formatDate(new Date(), DateUtil.TIME_PATTERN_YMD)+"/DEVICEID-"+ deviceId+".txt";
        String fileDir = DateUtil.formatDate(new Date(), DateUtil.TIME_PATTERN_YMD);
        FileWriter fileWriter = null;
        try {
            String filePath = myLogPath+"/"+fileName;
            String dirPath=myLogPath+"/"+fileDir;
            File file =new File(filePath);

            if(!file.exists()){//如果文件不存在
                //判断目录文件夹是否存在，不存在则创建
                File file2 = new File(dirPath);
                if (!file2.exists()) {
                    file2.mkdirs();
                }
                file.createNewFile();
            }
            fileWriter =new FileWriter(file, true);
            content = DateUtil.formatDate(new Date(), DateUtil.TIME_PATTERN_DISPLAY2)+" "+content +System.getProperty("line.separator");
            fileWriter.write(content);
            fileWriter.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(fileWriter!=null){
                    fileWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}